/***********************************************************************************************************************
 * kindeditor扩展，添加flash和多媒体上传功能,相关资源文件在plugins_jxhl/下，升级kindeditor时请保留此js和plugins_jxhl/
 * 
 * @author huangwq
 * @licence http://www.kindsoft.net/license.php
 **********************************************************************************************************************/

if (!window.KE) {
  alert('kindeditor-jxhlext.js must be placed after kindeditor.js');
}

KE.lang.invalidFlash = '请输入有效的URL地址。\n只允许swf格式。';

KE.lang.plugins.flash = {
  remoteFlash : '远程Flash',
  localFlash : '本地上传',
  remoteUrl : 'Flash地址',
  localUrl : 'Flash地址',
  width : '宽度',
  height : '高度',
  viewServer : '浏览...'
};

KE.lang.plugins.media = {
  remoteMedia : '远程媒体',
  localMedia : '本地上传',
  remoteUrl : '媒体地址',
  localUrl : '媒体地址',
  width : '宽度',
  height : '高度',
  autostart : '自动播放',
  viewServer : '浏览...'
};

KE.plugin.flash = {
  init : function(id) {
    var self = this;
    KE.g[id].getHtmlHooks.push(function(html) {
      return html.replace(/<img[^>]*class="?ke-flash"?[^>]*>/ig, function(imgStr) {
        var width = imgStr.match(/style="[^"]*;?\s*width:\s*(\d+)/i) ? RegExp.$1 : 0;
        var height = imgStr.match(/style="[^"]*;?\s*height:\s*(\d+)/i) ? RegExp.$1 : 0;
        width = width || (imgStr.match(/width="([^"]+)"/i) ? RegExp.$1 : 0);
        height = height || (imgStr.match(/height="([^"]+)"/i) ? RegExp.$1 : 0);
        if (imgStr.match(/kesrctag="([^"]+)"/i)) {
          var attrs = KE.util.getAttrList(unescape(RegExp.$1));
          attrs.width = width || attrs.width || 0;
          attrs.height = height || attrs.height || 0;
          attrs.kesrc = attrs.src;
          return KE.util.getMediaEmbed(attrs);
        }
      });
    });
    KE.g[id].setHtmlHooks.push(function(html) {
      return html.replace(/<embed[^>]*type="application\/x-shockwave-flash"[^>]*>(?:<\/embed>)?/ig, function($0) {
        var src = $0.match(/\s+src="([^"]+)"/i) ? RegExp.$1 : '';
        if ($0.match(/\s+kesrc="([^"]+)"/i)) {
          src = RegExp.$1;
        }
        var width = $0.match(/\s+width="([^"]+)"/i) ? RegExp.$1 : 0;
        var height = $0.match(/\s+height="([^"]+)"/i) ? RegExp.$1 : 0;
        var attrs = KE.util.getAttrList($0);
        attrs.src = src;
        attrs.width = width;
        attrs.height = height;
        return KE.util.getMediaImage(id, 'flash', attrs);
      });
    });
  },
  click : function(id) {
    KE.util.selection(id);
    var param = 'id=' + escape(id) + '&ver=' + escape(KE.version);
    this.dialog = new KE.dialog({
      id : id,
      cmd : 'flash',
      // file : 'flash.html',
      url : KE.scriptPath + 'plugins_jxhl/flash.html?' + param,
      width : 400,
      height : 140,
      loadingMode : true,
      title : KE.lang['flash'],
      yesButton : KE.lang['yes'],
      noButton : KE.lang['no']
    });
    this.dialog.show();
  },
  check : function(id, width, height) {
    var dialogDoc = KE.util.getIframeDoc(this.dialog.iframe);
    var type = KE.$('type', dialogDoc).value;
    var urlBox;
    if (type == 2) {
      urlBox = KE.$('imgFile', dialogDoc);
    } else {
      urlBox = KE.$('url', dialogDoc);
    }
    if (!urlBox.value.match(/^.{3,}$/)) {
      alert(KE.lang['invalidUrl']);
      KE.$('url', dialogDoc).focus();
      return false;
    }
    if (!width.match(/^\d*$/)) {
      alert(KE.lang['invalidWidth']);
      KE.$('width', dialogDoc).focus();
      return false;
    }
    if (!height.match(/^\d*$/)) {
      alert(KE.lang['invalidHeight']);
      KE.$('height', dialogDoc).focus();
      return false;
    }
    if (!urlBox.value.match(/\.(swf)(\s|\?|$)/i)) {
      alert(KE.lang['invalidFlash']);
      urlBox.focus();
      return false;
    }
    return true;
  },
  exec : function(id) {
    var self = this;
    var dialogDoc = KE.util.getIframeDoc(this.dialog.iframe);
    var type = KE.$('type', dialogDoc).value;
    var width = KE.$('width', dialogDoc).value;
    var height = KE.$('height', dialogDoc).value;
    if (!this.check(id, width, height)) {
      return false;
    }
    if (type == 2) {
      KE.$('editorId', dialogDoc).value = id;
      var uploadIframe = KE.$('uploadIframe', dialogDoc);
      KE.util.showLoadingPage(id);
      var onloadFunc = function() {
        KE.event.remove(uploadIframe, 'load', onloadFunc);
        KE.util.hideLoadingPage(id);
        var uploadDoc = KE.util.getIframeDoc(uploadIframe);
        var data = '';
        try {
          data = KE.util.parseJson(uploadDoc.body.innerHTML);
        } catch (e) {
          alert(KE.lang.invalidJson);
        }
        if (typeof data === 'object' && 'error' in data) {
          if (data.error === 0) {
            var url = KE.format.getUrl(data.url, 'original');
            self.insert(id, url, width, height);
          } else {
            alert(data.message);
            return false;
          }
        }
      };
      KE.event.add(uploadIframe, 'load', onloadFunc);
      dialogDoc.uploadForm.submit();
      return;
    } else {
      var url = KE.$('url', dialogDoc).value;
      this.insert(id, url, width, height);
    }
  },
  insert : function(id, url, width, height) {
    var html = KE.util.getMediaImage(id, 'flash', {
      src : url,
      type : KE.g[id].mediaTypes['flash'],
      width : width,
      height : height,
      quality : 'high'
    });
    KE.util.insertHtml(id, html);
    this.dialog.hide();
    KE.util.focus(id);
  }
};

KE.plugin.image = {
  getSelectedNode : function(id) {
    var g = KE.g[id];
    var startNode = g.keRange.startNode;
    var endNode = g.keRange.endNode;
    if (!KE.browser.WEBKIT && !g.keSel.isControl) {
      return;
    }
    if (startNode.nodeType != 1) {
      return;
    }
    if (startNode.tagName.toLowerCase() != 'img') {
      return;
    }
    if (startNode != endNode) {
      return;
    }
    if (!startNode.className.match(/^ke-\w+/i)) {
      return startNode;
    }
  },
  init : function(id) {
    var self = this;
    var g = KE.g[id];
    g.contextmenuItems.push({
      text : KE.lang['editImage'],
      click : function(id, menu) {
        KE.util.select(id);
        menu.hide();
        self.click(id);
      },
      cond : function(id) {
        return self.getSelectedNode(id);
      },
      options : {
        width : '150px',
        iconHtml : '<span class="ke-common-icon ke-common-icon-url ke-icon-image"></span>'
      }
    });
    g.contextmenuItems.push({
      text : KE.lang['deleteImage'],
      click : function(id, menu) {
        KE.util.select(id);
        menu.hide();
        var img = self.getSelectedNode(id);
        img.parentNode.removeChild(img);
        KE.util.execOnchangeHandler(id);
      },
      cond : function(id) {
        return self.getSelectedNode(id);
      },
      options : {
        width : '150px'
      }
    });
    g.contextmenuItems.push('-');
  },
  click : function(id) {
    KE.util.selection(id);
    this.dialog = new KE.dialog({
      id : id,
      cmd : 'image',
      file : 'image/image.html',
      width : 400,
      height : 220,
      loadingMode : true,
      title : KE.lang['image'],
      yesButton : KE.lang['yes'],
      noButton : KE.lang['no']
    });
    this.dialog.show();
  },
  check : function(id) {
    var dialogDoc = KE.util.getIframeDoc(this.dialog.iframe);
    var type = KE.$('type', dialogDoc).value;
    var width = KE.$('imgWidth', dialogDoc).value;
    var height = KE.$('imgHeight', dialogDoc).value;
    var title = KE.$('imgTitle', dialogDoc).value;
    var urlBox;
    if (type == 2) {
      urlBox = KE.$('imgFile', dialogDoc);
    } else {
      urlBox = KE.$('url', dialogDoc);
    }
    if (!urlBox.value.match(/\.(jpg|jpeg|gif|bmp|png)(\s|\?|$)/i)) {
      alert(KE.lang['invalidImg']);
      urlBox.focus();
      return false;
    }
    if (!width.match(/^\d*$/)) {
      alert(KE.lang['invalidWidth']);
      KE.$('imgWidth', dialogDoc).focus();
      return false;
    }
    if (!height.match(/^\d*$/)) {
      alert(KE.lang['invalidHeight']);
      KE.$('imgHeight', dialogDoc).focus();
      return false;
    }
    return true;
  },
  exec : function(id) {
    var self = this;
    var dialogDoc = KE.util.getIframeDoc(this.dialog.iframe);
    var type = KE.$('type', dialogDoc).value;
    var width = KE.$('imgWidth', dialogDoc).value;
    var height = KE.$('imgHeight', dialogDoc).value;
    var title = KE.$('imgTitle', dialogDoc).value;
    var alignElements = dialogDoc.getElementsByName('align');
    var align = '';
    for ( var i = 0, len = alignElements.length; i < len; i++) {
      if (alignElements[i].checked) {
        align = alignElements[i].value;
        break;
      }
    }
    if (!this.check(id)) {
      return false;
    }
    if (type == 2) {
      KE.$('editorId', dialogDoc).value = id;
      var uploadIframe = KE.$('uploadIframe', dialogDoc);
      KE.util.showLoadingPage(id);
      var onloadFunc = function() {
        KE.event.remove(uploadIframe, 'load', onloadFunc);
        KE.util.hideLoadingPage(id);
        var uploadDoc = KE.util.getIframeDoc(uploadIframe);
        var data = '';
        try {
          data = KE.util.parseJson(uploadDoc.body.innerHTML);
        } catch (e) {
          alert(KE.lang.invalidJson);
        }
        if (typeof data === 'object' && 'error' in data) {
          if (data.error === 0) {
            var url = KE.format.getUrl(data.url, 'original');
            self.insert(id, url, title, width, height, 0, align);
          } else {
            alert(data.message);
            return false;
          }
        }
      };
      KE.event.add(uploadIframe, 'load', onloadFunc);
      dialogDoc.uploadForm.submit();
      return;
    } else {
      var url = KE.$('url', dialogDoc).value;
      this.insert(id, url, title, width, height, 0, align);
    }
  },
  insert : function(id, url, title, width, height, border, align) {
    var html = '<img src="' + url + '" kesrc="' + url + '" ';
    if (width > 0) {
      html += 'width="' + width + '" ';
    }
    if (height > 0) {
      html += 'height="' + height + '" ';
    }
    if (title) {
      html += 'title="' + title + '" ';
    }
    if (align) {
      html += 'align="' + align + '" ';
    }
    html += 'alt="' + title + '" ';
    if (border) {
      html += 'border="' + border + '" ';
    }
    html += '/>';
    KE.util.insertHtml(id, html);
    this.dialog.hide();
    KE.util.focus(id);
  }
};

KE.plugin.media = {
  init : function(id) {
    var self = this;
    var typeHash = {};
    KE.each(KE.g[id].mediaTypes, function(key, val) {
      typeHash[val] = key;
    });
    KE.g[id].getHtmlHooks.push(function(html) {
      return html.replace(/<img[^>]*class="?ke-\w+"?[^>]*>/ig, function($0) {
        var width = $0.match(/style="[^"]*;?\s*width:\s*(\d+)/i) ? RegExp.$1 : 0;
        var height = $0.match(/style="[^"]*;?\s*height:\s*(\d+)/i) ? RegExp.$1 : 0;
        width = width || ($0.match(/width="([^"]+)"/i) ? RegExp.$1 : 0);
        height = height || ($0.match(/height="([^"]+)"/i) ? RegExp.$1 : 0);
        if ($0.match(/\s+kesrctag="([^"]+)"/i)) {
          var attrs = KE.util.getAttrList(unescape(RegExp.$1));
          attrs.width = width || attrs.width || 0;
          attrs.height = height || attrs.height || 0;
          attrs.kesrc = attrs.src;
          return KE.util.getMediaEmbed(attrs);
        }
      });
    });
    KE.g[id].setHtmlHooks.push(function(html) {
      return html.replace(/<embed[^>]*type="([^"]+)"[^>]*>(?:<\/embed>)?/ig, function($0, $1) {
        if (typeof typeHash[$1] == 'undefined') {
          return $0;
        }
        var src = $0.match(/\s+src="([^"]+)"/i) ? RegExp.$1 : '';
        if ($0.match(/\s+kesrc="([^"]+)"/i)) {
          src = RegExp.$1;
        }
        var width = $0.match(/\s+width="([^"]+)"/i) ? RegExp.$1 : 0;
        var height = $0.match(/\s+height="([^"]+)"/i) ? RegExp.$1 : 0;
        var attrs = KE.util.getAttrList($0);
        attrs.src = src;
        attrs.width = width;
        attrs.height = height;
        return KE.util.getMediaImage(id, '', attrs);
      });
    });
  },
  click : function(id) {
    KE.util.selection(id);
    var param = 'id=' + escape(id) + '&ver=' + escape(KE.version);
    this.dialog = new KE.dialog({
      id : id,
      cmd : 'media',
      // file : 'media.html',
      url : KE.scriptPath + 'plugins_jxhl/media.html?' + param,
      width : 400,
      height : 170,
      loadingMode : true,
      title : KE.lang['media'],
      yesButton : KE.lang['yes'],
      noButton : KE.lang['no']
    });
    this.dialog.show();
  },
  check : function(id, width, height) {
    var dialogDoc = KE.util.getIframeDoc(this.dialog.iframe);
    var type = KE.$('type', dialogDoc).value;
    var urlBox;
    if (type == 2) {
      urlBox = KE.$('imgFile', dialogDoc);
    } else {
      urlBox = KE.$('url', dialogDoc);
    }
    if (!urlBox.value.match(/^.{3,}\.(swf|flv|mp3|wav|wma|wmv|mid|avi|mpg|mpeg|asf|rm|rmvb)(\?|$)/i)) {
      alert(KE.lang['invalidMedia']);
      urlBox.focus();
      return false;
    }
    if (!width.match(/^\d*$/)) {
      alert(KE.lang['invalidWidth']);
      KE.$('width', dialogDoc).focus();
      return false;
    }
    if (!height.match(/^\d*$/)) {
      alert(KE.lang['invalidHeight']);
      KE.$('height', dialogDoc).focus();
      return false;
    }
    return true;
  },
  exec : function(id) {
    var self = this;
    var dialogDoc = KE.util.getIframeDoc(this.dialog.iframe);
    var type = KE.$('type', dialogDoc).value;
    var width = KE.$('width', dialogDoc).value;
    var height = KE.$('height', dialogDoc).value;
    var autostart = KE.$('autostart', dialogDoc).checked ? 'true' : 'false';
    if (!this.check(id, width, height)) {
      return false;
    }
    if (type == 2) {
      KE.$('editorId', dialogDoc).value = id;
      var uploadIframe = KE.$('uploadIframe', dialogDoc);
      KE.util.showLoadingPage(id);
      var onloadFunc = function() {
        KE.event.remove(uploadIframe, 'load', onloadFunc);
        KE.util.hideLoadingPage(id);
        var uploadDoc = KE.util.getIframeDoc(uploadIframe);
        var data = '';
        try {
          data = KE.util.parseJson(uploadDoc.body.innerHTML);
        } catch (e) {
          alert(KE.lang.invalidJson);
        }
        if (typeof data === 'object' && 'error' in data) {
          if (data.error === 0) {
            var url = KE.format.getUrl(data.url, 'original');
            self.insert(id, url, width, height, autostart);
          } else {
            alert(data.message);
            return false;
          }
        }
      };
      KE.event.add(uploadIframe, 'load', onloadFunc);
      dialogDoc.uploadForm.submit();
      return;
    } else {
      var url = KE.$('url', dialogDoc).value;
      this.insert(id, url, width, height, autostart);
    }
  },
  insert : function(id, url, width, height, autostart) {
    var html = KE.util.getMediaImage(id, '', {
      src : url,
      type : KE.g[id].mediaTypes[KE.util.getMediaType(url)],
      width : width,
      height : height,
      autostart : autostart,
      loop : 'true'
    });
    KE.util.insertHtml(id, html);
    this.dialog.hide();
    KE.util.focus(id);
  }
};